$(document).ready(function(){
	var df = $("input[name=domesticOrForeign]:radio:checked").val();
	if (df === null || df === undefined) {
		$(".form-group.form-country").hide();
		$(".form-group.form-area").hide();
	} else if (df == 0) {
		$(".form-group.form-country").hide();
	} else if (df == 1) {
		$(".form-group.form-area").hide();
	}
	
	/*使按钮固定居中*/
	var width = $("div[class=box-footer]").css("width");
	if (width !== null && width !== undefined) {
		var wid = width.replace("px", "")-230;
		$("div.box-footer").css("width", wid);
	}
	
	/*检查查看联系方式时是否需要输入密码*/
	var isLook = $("input:hidden#isLook").val();
	var isSign = $("input:hidden#isSign").val();
	var isLookPwd = $("input:hidden#isLookPwd").val();
	if (isLookPwd != null && isLookPwd != '' && isLookPwd == 0)
		alert("密码错误");
	
	if (isLook == 1 && isSign == 1) {
		$("#lookExpertPwd").show();
	} else {
		$("#lookExpertPwd").hide();
		if (isLook != null && isLook != '' && isLook == 0)
			alert("今日已达查看上限");
	}
	
});

/**
 * 使按钮固定居中
 */
$("a.sidebar-toggle").mouseup(function() {
	if ($("body").hasClass("sidebar-collapse")) {
		var wid = $("div[class=box-footer]").css("width").replace("px", "")-230;
		$("div[class=box-footer]").css("width", wid);
	} else {
		$("div[class=box-footer]").removeAttr("style");
	}
});


/**
 * 初始化地区，只要引入该js即可实现三级联动
 */
$("#provinceId").change(function () {
	$.get("/area/getCityByProvinceId/" + $("#provinceId").val(), function (data) {
		if (data.status) {
			var result = "<option>选择城市</option>";
			$.each(data.obj, function (n, value) {
				result += "<option value='" + value.names + "'>" + value.worth +
				"</option>";
			});
			$("#cityId").html('');
			$("#areaId").html('');
			$("#cityId").append(result);
		}
	}, "json");
});
$("#cityId").change(function () {
	$.get("/area/getAreaByCityId/" + $("#cityId").val(), function (data) {
		if (data.status) {
			var result = "<option>选择区域</option>";
			$.each(data.obj, function (n, value) {
				result += "<option value='" + value.names + "'>" + value.worth +
				"</option>";
			});
			$("#areaId").html('');
			$("#areaId").append(result);
		}
	}, "json");
});


/**
 * 搜索表单提交时触发该事件
 * 用来检验输入值
 */
$(".content.container-fluid form#from1").submit(function() {
	addAreaName();
	return true;
});

$("#optionsRadios1").change(function() {
	$(".form-group.form-country select").val(-1);
	$(".form-group.form-country").hide();
	$(".form-group.form-area").show();
});
$("#optionsRadios2").change(function() {
	$(".form-group.form-area select").val(-1);
	$(".form-group.form-area").hide();
	$(".form-group.form-country").show();
});

/**
 * 非搜索表单提交时触发该事件
 * 用来检验输入值
 */
$(".content.container-fluid form#form1").submit(function() {
	var areaNotEmpty = checkArea();
	var contactNotEmpty = checkContact();
	return areaNotEmpty && contactNotEmpty;
});

function checkArea() {
	var areaLen = $(".form-group.form-area").length;
	if (areaLen === 0)
		return true;
	//先给area添加name属性
	addAreaName();
	//校验
	var areaNum = $(".form-group select[name=area]").val();
	if (areaNum !== undefined && areaNum !== null && areaNum > 0)
		return true;
	else {
		var countryVal = $("span#countryEmpty").text();
		if (countryVal === null || countryVal === undefined || countryVal === "")
			$(".form-group:contains('国家') label:first").after("<span id='countryEmpty' style='color: red;'>请选择一个国家</span>");
		var areaVal = $("span#areaEmpty").text();
		if (areaVal === null || areaVal === undefined || areaVal === "")
			$(".form-group:contains('省') label:first").after("<span id='areaEmpty' style='color: red;'>至少选择一个地区</span>");
		return false;
	}
}

function checkContact() {
	var $contactArr = $("input.form-control.contact");
	var len = $contactArr.length;
	//没有找到联系方式就不校验
	if (len == 0) 
		return true;
	for (var i = 0; i < len; i++) {
		var contact = $($contactArr.get(i)).val();
		if (contact !== null && contact !== "")
			return true;
	}
	var conVal = $("span#contactEmpty").text();
	if (conVal === null || conVal === undefined || conVal === "") 
		$("input.form-control.contact:first").before("<span id='contactEmpty' style='color: red;'>至少有一个联系方式</span>");
	return false;
}

/**
 * 给最具体的一个地区下拉框添加一个name属性，在提交的时候调用
 * 如果没有选择地区，后台是接收不到值的
 */
function addAreaName() {
	var $area = $("select.form-area");
	var areaNum = $area.length;
	for (var i = areaNum - 1; i > -1; i--) {
		var $perArea = $($area.get(i));
		var areaVal = $perArea.val();
		if (areaVal > 0) {
			$perArea.attr("name", "area");
			return;
		}
	} 
}

//复选框全选
$(":checkbox#all, :checkbox.sign").click(function() {
    $("input.matched:not(:disabled)").prop("checked", this.checked);
});

function matchButt(matchUrl) {
	$("#dosubmit").click(function() {
		matching(matchUrl);
	});
}

function matching(matchUrl) {
	$("input.matched:checked").each(function(index) {
		var data = $(this).val();
		$.ajax({
			url : matchUrl,
			data : data,
			success : function(msg) {
				if ($("input.matched:checked").length-1 === index && msg === 'success') {
					alert("匹配成功");
					$("input.matched:checked").each(function() {
						$(this).parent().parent().css("color", "gray");
					});                        	
					$("input.matched:checked").prop("disabled", true);                        	
					$("input.matched:checked").prop("checked", false);                        	
				}
				
				if ($("input.matched:checked").length-1 === index && msg === 'successTuiSong') {
					alert("推送成功");
					$("input.matched:checked").each(function() {
						$(this).parent().parent().css("color", "gray");
					});                        	
					$("input.matched:checked").prop("disabled", true);                        	
					$("input.matched:checked").prop("checked", false);                        	
				}
			}
		}); 
	});
}

function matchWithData(matchUrl, data) {
	$.ajax({
		url : matchUrl,
		data : data,
		success : function(msg) {
			if (msg === 'success') {
				alert("匹配成功");
			}
		}
	}); 
}

$(":reset").click(function() {
	var $form = $($(this).closest("form"));
	$form.find(":text").attr("value", "");
	$form.find(":checked").attr("checked", false);
	$form.find(":selected").attr("selected", false);
});

$("input[name=demandMatch]:not(:checked)").click(function() {
	var url = $(this).val();
	window.location.href = $(this).val();
});

$("input#more").click(function() {
	$(".contact-hide").toggle();
	var title = $(this).val();
	if (title === '更多信息')
		$(this).val("收回");
	else
		$(this).val("更多信息");
});


/**
 * 专家管理页面批量关注
 * @param matchUrl
 */
function batchFocus(matchUrl) {
	$("#batchFocus").click(function() {
		batchFocus1(matchUrl);
	});
}
function batchFocus1(matchUrl) {
	$("input.matched:checked").each(function(index) {
		//获取专家的pid
		var data = $(this).val();
		$.ajax({
			url : matchUrl,
			data : data,
			success : function(msg) {
				if ($("input.matched:checked").length-1 === index) {
					//弹出后台的提示信息
					alert(msg.obj);
					$("input.matched:checked").prop("disabled", true);                        	
					$("input.matched:checked").prop("checked", false);
				}
			}
		}); 
		//批量关注后同时将关注改为取消关注
		var ind = data.indexOf("=")+1;
		var id = data.substring(ind);
		var clickVal = $("a#"+id).attr("onclick");
		$("a#"+id).attr("onclick", clickVal.replace("subscribe1", "delSub1"));
		$("a#"+id).text("取消关注");
	});
}

/**
 * @param pid 主键，如项目id，需求ID等
 * @param order 1：添加项目联系人  2：添加需求联系人   3：添加项目持有人	
 * 4：修改项目联系人		5：修改需求联系人		6:修改项目持有人
 * @returns
 */
function linkPerson(pid, order) {
	$("input[name=name]").change(function() {
		var name = $.trim($(this).val());
		checkName(pid, order, name);
	});
}

function checkName(pid, order, name) {
	if (name) {
		$.ajax({
			url : '/person/checkName',
			data : {name : name},
			success : function(data) {
				if (data.length > 0)
					createTable(data, pid, order);
			}
		});
	}
}

function createTable(data, pid, order) {
	var table = "<table class='table table-bordered'>";
	table += "<tr><th></th><th>ID</th><th>姓名</th><th>手机</th><th>邮箱</th><th>固定电话</th><th>微信</th><th>其他联系方式</th></tr>";
	for (var i = 0; i < data.length; i++) {
		var per = data[i];
		table += "<tr><td><input type=radio value="+per.pid+" name=checkPerson></td><td>E"+trim(per.expertNumber)+"</td><td>"+trim(per.name)+"</td><td>"+trim(per.tell)+"</td><td>"+trim(per.email)+"</td><td>"+trim(per.fixedPhone)+"</td><td>"+trim(per.wechat)+"</td><td>"+trim(per.otherContact)+"</td></tr>";
	}
	table += "</table>";
	layx.html("person-tab", "选择一个专家", table, {
		statusBar:true,
		buttons:[
			{
				label : '关联',
				id : "link",
				callback : function(id, button, event) {
					layx.destroy(id, "link");
				}
			},
			{
				label : '修改',
				id : "update",
				callback : function(id, button, event) {
					layx.destroy(id, "update");
				}
			},
			{
				label : '取消',
				id : "cancel",
				callback : function(id, button, event) {
					layx.destroy(id, "cancel");
				}
			}
		],
		event:{
			ondestroy:{
				before:function(layxWindow, winform, params, inside, escKey) {
					var personId = $(layxWindow).find(":checked").val();
					if ((personId === undefined || personId === null) && (params === "link" || params === 'update')) {
						layx.msg("请选择一个专家");
						return false;
					}
					if (params === "link") {
						if (order === 1 || order === 4) 
							window.location.href = '/project/linkContact?projectId='+pid+'&personId='+personId;
						else if (order === 2 || order === 5)
							window.location.href = '/demand/linkContact?demandId='+pid+'&personId='+personId;
						else if (order === 3 || order === 6)
							window.location.href = '/project/linkHolder1?projectId='+pid+'&personId='+personId;
					} else if (params === "update") {
						if (order === 1 || order === 4) 
							window.location.href = '/project/showLinkUpdateContact?projectId='+pid+'&projectContactId='+personId;
						else if (order === 2 || order === 5) 
							window.location.href = '/demand/showLinkUpdateContact?demandId='+pid+'&demandContactId='+personId;
						else if (order === 3 || order === 6)
							window.location.href = '/project/showLinkUpdateHolder1?projectId='+pid+'&personId='+personId;
					}
				}
			}
		}	
	});
}

function trim(obj) {
	return obj ? obj : "";
}

$("input[name=projectName]").change(function() {
	var projectName = $.trim($(this).val());
	if (projectName) {
		$.ajax({
			url : '/project/checkName',
			data : {projectName : projectName},
			success : function(data) {
				if (data.length > 0)
					createProjectTable(data);
			}
		});
	}
});

function createProjectTable(data) {
	var table = "<table class='table table-bordered'>";
	table += "<tr><th></th><th>ID</th><th>名称</th><th>类型</th><th>状态</th>";
	for (var i = 0; i < data.length; i++) {
		var pro = data[i];
		table += "<tr><td><input type=radio value="+pro.pid+" name=checkPerson></td><td>R"+trim(pro.projectNumber)+"</td><td>"+trim(pro.projectName)+"</td><td>"+trim(pro.projectType)+"</td><td>"+trim(pro.projectStatusWorth)+"</td></tr>";
	}
	table += "</table>";
	layx.html("project-tab", "选择一个项目", table, {
		statusBar:true,
		buttons:[
			{
				label : '修改',
				id : "update",
				callback : function(id, button, event) {
					layx.destroy(id, "update");
				}
			},
			{
				label : '取消',
				id : "cancel",
				callback : function(id, button, event) {
					layx.destroy(id, "cancel");
				}
			}
		],
		event:{
			ondestroy:{
				before:function(layxWindow, winform, params, inside, escKey) {
					var projectId = $(layxWindow).find(":checked").val();
					if ((projectId === undefined || projectId === null) && params === 'update') {
						layx.msg("请选择一个项目");
						return false;
					}
					if (params === "update") {
						window.location.href = '/project/showUpdate?projectId='+projectId;
					}
				}
			}
		}	
	});
}

/**
 * 添加需求时查找重名的
 * @returns
 */
$("input[name=demandName]").change(function() {
	var demandName = $.trim($(this).val());
	if (demandName) {
		$.ajax({
			url : '/demand/checkName',
			data : {demandName : demandName},
			success : function(data) {
				if (data.length > 0)
					createDemandTable(data);
			}
		});
	}
});

function createDemandTable(data) {
	var table = "<table class='table table-bordered'>";
	table += "<tr><th></th><th>ID</th><th>名称</th><th>类型</th><th>状态</th>";
	for (var i = 0; i < data.length; i++) {
		var dem = data[i];
		table += "<tr><td><input type=radio value="+dem.pid+" name=checkPerson></td><td>D"+trim(dem.demandNumber)+"</td><td>"+trim(dem.demandName)+"</td><td>"+trim(dem.demandType)+"</td><td>"+trim(dem.demandStatusWorth)+"</td></tr>";
	}
	table += "</table>";
	layx.html("project-tab", "选择一个需求", table, {
		statusBar:true,
		buttons:[
			{
				label : '修改',
				id : "update",
				callback : function(id, button, event) {
					layx.destroy(id, "update");
				}
			},
			{
				label : '取消',
				id : "cancel",
				callback : function(id, button, event) {
					layx.destroy(id, "cancel");
				}
			}
			],
			event:{
				ondestroy:{
					before:function(layxWindow, winform, params, inside, escKey) {
						var demandId = $(layxWindow).find(":checked").val();
						if ((demandId === undefined || demandId === null) && params === 'update') {
							layx.msg("请选择一个需求");
							return false;
						}
						if (params === "update") {
							window.location.href = '/demand/showUpdate?demandId='+demandId;
						}
					}
				}
			}	
	});
}

function lookExpert(url) {
	var pwd = $("#lookExpertPwd").val();
	window.location.href=url+"&lookPwd="+pwd;
}

$("#userGroup .btn.btn-primary").click(function() {
	var groupNameId = $("#userGroup select[name=groupNameId]").val();
	var position = $("#userGroup select[name=position]").val();
	$(".matched:checked").each(function(index) {
		var userId = $(this).val();
		$.ajax({
			url : '/user/addToUserGroup',
			data : 'groupNameId='+groupNameId+'&position='+position+'&userId='+userId,
			success : function(msg) {
				if ($("input.matched:checked").length-1 === index && msg === 'success') {
					alert("用户成功加入到分组");
					$("input:checked").prop("checked", false);
					location.reload();
				}
			}
		});
	});
});

function deleteFromUserGroup(userId, fullName) {
	$.ajax({
		url : '/user/queryUserGroup',
		data : {userId : userId},
		success : function(data) {
			if (data.length > 0)
				createUserGroupTable(data, fullName);
		}
	});
}

function createUserGroupTable(data, fullName) {
	var table = "<h4>"+fullName+":</h4>";
	table += "<table class='table table-bordered'>";
	table += "<tr><th></th><th>分组</th><th>身份</th></tr>";
	for (var i = 0; i < data.length; i++) {
		var ug = data[i];
		table += "<tr><td><input type=checkbox value="+ug.pid+"></td><td>"+ug.groupName+"</td><td>"+ug.positionName+"</td></tr>";
	}
	table += "</table>";
	layx.html("userGroup-tab", "移出分组", table, {
		statusBar:true,
		buttons:[
			{
				label : '移出',
				id : "remove",
				callback : function(id, button, event) {
					layx.destroy(id, "remove");
				}
			},
			{
				label : '取消',
				id : "cancel",
				callback : function(id, button, event) {
					layx.destroy(id, "cancel");
				}
			}
			],
			event:{
				ondestroy:{
					before:function(layxWindow, winform, params, inside, escKey) {
						var checkedEles = $(layxWindow).find(":checked");
						if (($(checkedEles).length <= 0) && params === 'remove') {
							layx.msg("至少选择一项");
							return false;
						}
						if (params === "remove") {
							$(checkedEles).each(function() {
								var userGroupId = $(this).val();
								$.get("/user/removeFromUserGroup", {"userGroupId" : userGroupId});
							});
							location.reload();
						}
					}
				}
			}	
	});
}


